import { buffer, util } from '@kit.ArkTS';

export class StringCodecManager {
  /**
   * 将base64字符串,转换为二进制数据
   * @param str
   * @param charset
   * @returns
   */
  static base64Decode(
    str: string
  ): Uint8Array {
    const buff = buffer.from(str, 'base64');
    return new Uint8Array(buff.buffer)
  }

  /**
   * 对二进制的unicode序列编码
   * 编码是对一个字符串进行编码,得到其编码序列.
   * 输入值,本身是一种编码的字符串.
   * @param u8a
   */
  static encode(u8a) {
    let encoder = util.TextEncoder.create("gb2312");
    encoder.encodeInto();
  }

  /**
   * 将一个 编码的字符串序列 解码得到字符串(unicode序列?)
   *
   * "gb2312"
   */
  static decode(u8a: Uint8Array, charset: string = "utf-8"): string {
    let decoder = util.TextDecoder.create(charset)
    return decoder.decodeWithStream(u8a);
  }

  //默认是得到utf的字符串
  static u8aToString(u8a: Uint8Array): string {
    let u8aBuffer = buffer.from(u8a);
    return u8aBuffer.toString()
  }

  /**
   * 一个u8高4位用一个char,低4位用一个char进行显示.
   * B1H4 B1L4 B2H4 B2L4 ...
   * @param u8a
   * @returns
   */
  static u8aToString_oneByteToTwoChar(u8a: Uint8Array): string {
    if (u8a.length == 0) {
      return "";
    }
    let string = "";
    for (let i = 0; i <= u8a.length - 1; i++) {
      let u8 = u8a[i];
      let h4 = u8 >>> 4;
      let l4 = u8 & 0x0f
      string += String.fromCharCode(h4);
      string += String.fromCharCode(l4);
    }
    return string;
  }

  /**
   * u8a 显示其值的字符串序列,radix是进制.
   * @param u8a
   * @returns
   */
  static u8aToString_valueDisplay(u8a: Uint8Array, radix: number = 10): string {
    if (u8a.length == 0) {
      return "";
    }
    let string = "";
    for (let i = 0; i <= u8a.length - 1; i++) {
      let u8 = u8a[i];
      string += u8.toString(radix);
    }
    return string;
  }

  static u8aToBase64string(u8a: Uint8Array): string {
    let base64HP = new util.Base64Helper();
    let encodeU8a = base64HP.encodeSync(u8a);
    return StringCodecManager.u8aToString(encodeU8a)
  }

  static stringToU8aWithUtf8(str: string): Uint8Array {
    let textEncoder = new util.TextEncoder("utf-8");
    let u8a = textEncoder.encodeInto(str);
    return u8a;
  }

  /**
   * 将每个uint作为一个数字,用其字符串=展示出来.
   * @param u8a
   * @returns
   */
  static getU8aDisplayString(u8a: Uint8Array, seperator = ","): string {
    if (u8a.length == 0) {
      return "";
    }
    let string = "";
    for (let i = 0; i <= u8a.length - 1; i++) {
      let u8 = u8a[i];
      string += u8.toString()
      if (i != u8a.length - 1) {
        string += seperator
      }
    }
    return string;
  }
}